<template>
	<div>
		<div class="">
			<van-form @submit="onSubmit">
				<van-field label="用户" v-model="regForm.name" type="text" placeholder="请输入用户"
					:rules="[{ pattern:regNamePwd,required: true, message: '无效用户名' }]" />

				<van-field label="密码" v-model="regForm.password" type="password" placeholder="请输入密码"
					:rules="[{ pattern:regNamePwd,required: true, message: '无效密码' }]" />

				<van-field label="确认" v-model="regForm.password2" type="password" placeholder="请确认密码"
					:rules="[{ pattern:regNamePwd,required: true, message: '无效密码' }]" />

				<van-field label="邮箱" v-model="regForm.email" type="email" placeholder="请输入邮箱"
					:rules="[{ pattern:regEmail, message: '无效邮箱' }]" />

				<van-field label="电话" v-model="regForm.phone" type="tel" placeholder="请输入电话"
					:rules="[{ pattern:regPhone, message: '无效手机号码' }]" />

				<van-field name="radio" label="性别">
					<template #input>
						<van-radio-group v-model="regForm.gender" direction="horizontal">
							<van-radio :name="1">男</van-radio>
							<van-radio :name="0">女</van-radio>
						</van-radio-group>
					</template>
				</van-field>
				<van-field label="昵称" v-model="regForm.nick_name" type="text" placeholder="请输入昵称"
				/>				
				<van-field name="uploader" label="头像">
					<template #input>
						<van-uploader 
							name="avatar" 
							v-model="avatarList" 
							:max-count="1" 
							:after-read="afterRead"
							:disabled="isUploading"
						/>
						<div v-if="avatarList.length > 0 && avatarList[0].status" class="mt-2 text-sm">
							<span v-if="avatarList[0].status === 'uploading'" class="text-primary">
								<i class="fa fa-spinner fa-spin mr-1"></i>{{ avatarList[0].message }}
							</span>
							<span v-else-if="avatarList[0].status === 'success'" class="text-success">
								<i class="fa fa-check-circle mr-1"></i>{{ avatarList[0].message }}
							</span>
							<span v-else class="text-danger">
								<i class="fa fa-exclamation-circle mr-1"></i>{{ avatarList[0].message }}
								<button class="ml-2 text-primary" @click="retryUpload">重试</button>
							</span>
						</div>
					</template>
				</van-field>

				<div style="margin: 16px;">
					<van-button round block type="info" native-type="submit">提交</van-button>
				</div>

			</van-form>
			<div class="content-padded">
				<p>注册成功后的用户可用于登录</p>
			</div>
		</div>
	</div>
</template>

<script>
	import {
		register,
		uploadAvatar
	} from "@/api/user.js";
import {setUserLocal} from '@/utils/auth'
	export default {
		data() {
			return {
				regForm: { 
					name: "",
					password: "",
					password2: "",
					email: "",
					phone: "",
					gender: 1,
					avatar: "",
					nick_name:""  
				},
				avatarList: [],
				lastUploadFile: null, // 保存最后一次上传的文件
				//规则:字母数字‘6~12				
				regNamePwd: /^[a-z0-9]{3,12}$/i,
				regPhone: /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8}$/,
				regEmail: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
			};
		},
		computed: {
			// 计算属性：是否正在上传
			isUploading() {
				return this.avatarList.length > 0 && this.avatarList[0].status === 'uploading';
			}
		},
		methods: {
			//手动处理文件上传
			afterRead(file) {
				// 保存文件用于重试
				this.lastUploadFile = file;
				
				// 立即更新上传状态
				this.avatarList = [{
					url: '',
					status: 'uploading',
					message: '上传中...'
				}];

				// 设置超时计时器（30秒）
				const timeoutId = setTimeout(() => {
					if (this.isUploading) {
						this.avatarList[0].status = 'failed';
						this.avatarList[0].message = '上传超时，请重试';
						this.$toast('上传超时，请检查网络');
					}
				}, 30000);

				// 执行上传请求
				uploadAvatar(file.file)
					.then(result => {
						// 清除超时计时器
						clearTimeout(timeoutId);
						
						// 构建完整URL
						const fullUrl = this.APIDomainName + result.url;
						
						// 更新头像列表和表单数据
						this.avatarList = [{
							url: fullUrl,
							status: 'success',
							message: '上传成功'
						}];
						
						this.regForm.avatar = result.url;
						this.$toast.success('头像上传成功');
					})
					.catch(error => {
						// 清除超时计时器
						clearTimeout(timeoutId);
						
						console.error('头像上传失败:', error);
						
						// 显示错误状态
						this.avatarList = [{
							url: '',
							status: 'failed',
							message: '上传失败，请重试'
						}];
						
						// 根据错误类型显示不同的提示
						if (error.response) {
							this.$toast(`上传失败: ${error.response.data.message || '服务器错误'}`);
						} else if (error.message) {
							this.$toast(`上传失败: ${error.message}`);
						} else {
							this.$toast('上传失败，请检查网络连接');
						}
					});
			},
			
			// 重试上传方法
			retryUpload() {
				if (this.lastUploadFile) {
					this.afterRead(this.lastUploadFile);
				}
			},

			//处理提交保存
			onSubmit() {
				if (this.regForm.password != this.regForm.password2) {
					this.$toast("密码两次输入不一致");
					return;				
				}

				//注意传递过去的参数user的属性名
				let user = this.regForm;
				delete user.password2; //删除该临时的字段
				register(user).then(result => {
					setUserLocal(result.data.user);
					this.$router.push({
						name: "login"
					});
				});
			},
		},
	};
</script>

<style lang="less" scoped>
	.content-padded {
		margin: 30px;
	}
</style>